#include "Stack.h"

void StackDestory(ST **phead)
{
    assert(phead);
    assert(*phead);

    ST *cur = *phead;
    while (cur)
    {
        ST *next = cur->next;
        free(cur);
        cur = next;
    }
    *phead = NULL;
}

void StackPush(ST **phead, STDataType x)
{
    assert(phead);
    ST *newnode = (ST *)malloc(sizeof(ST));
    if (newnode == NULL)
    {
        printf("malloc fail!!!\n");
        exit(EXIT_FAILURE);
    }
    newnode->next = NULL;
    newnode->data = x;

    if (*phead == NULL)
    {
        *phead = newnode;
    }
    else
    {
        newnode->next = *phead;
        *phead = newnode;
    }
}

void StackPop(ST **phead)
{
    assert(phead);
    // assert(*phead);

    if (*phead == NULL)
    {
        return;
    }
    else if ((*phead)->next == NULL)
    {
        free(*phead);
        *phead = NULL;
    }
    else
    {
        ST *next = (*phead)->next;
        free(*phead);
        *phead = next;
    }
}

bool StackEmpty(ST *phead)
{
    return phead == NULL;
}

int StackTop(ST *phead)
{
    assert(phead);
    return phead->data;
}

int main()
{
    ST *st = NULL;
    StackPush(&st, 1);
    StackPush(&st, 2);
    StackPush(&st, 3);
    StackPush(&st, 4);
    StackPush(&st, 5);
    StackPush(&st, 6);

    while (!StackEmpty(st))
    {
        printf("%d ", StackTop(st));
        StackPop(&st);
    }

    printf("\n");
    StackDestory(&st);
    return 0;
}